<!DOCTYPE html>
<title>Credential Manager: unit test for the Web Authentication Testing API.</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script type="module">
import {TestAuthenticatorManager} from './resources/virtual-navigator-credentials.js';

const manager = new TestAuthenticatorManager;

promise_test(async t => {
  let authenticators = await manager.authenticators();
  assert_equals(authenticators.length, 0);

  let testAuthenticator1 = await manager.createAuthenticator();
  let testAuthenticator2 = await manager.createAuthenticator();
  let id1 = await testAuthenticator1.id();
  let id2 = await testAuthenticator2.id();
  t.add_cleanup(() => manager.clearAuthenticators());

  authenticators = await manager.authenticators();
  assert_equals(authenticators.length, 2);

  assert_true(await manager.removeAuthenticator(id1));
  assert_false(await manager.removeAuthenticator(id1));

  authenticators = await manager.authenticators();
  assert_equals(authenticators.length, 1);
  assert_equals(await authenticators[0].id(), id2);

  await manager.clearAuthenticators();

  authenticators = await manager.authenticators();
  assert_equals(authenticators.length, 0);
}, "Methods of VirtualAuthenticatorManager work.");

promise_test(async t => {
  let testAuthenticator = await manager.createAuthenticator();
  t.add_cleanup(() => manager.clearAuthenticators());
  let id = await testAuthenticator.id();
  assert_equals(await testAuthenticator.uniqueId(), id);

  let keys = await testAuthenticator.registeredKeys();
  assert_equals(keys.length, 0);

  let keyHandle1 = new TextEncoder("utf-8").encode("foo");
  assert_true(await testAuthenticator.generateAndRegisterKey(keyHandle1, "test.domain"));

  // Re-registrations (with the same key handle) should not be allowed.
  assert_false(await testAuthenticator.generateAndRegisterKey(keyHandle1, "test.domain"));

  keys = await testAuthenticator.registeredKeys();
  assert_equals(keys.length, 1);

  assert_equals(keys[0].keyHandle.toString(), keyHandle1.toString());
  assert_equals(keys[0].counter, 1);

  let keyHandle2 = new TextEncoder("utf-8").encode("bar");
  assert_true(await testAuthenticator.generateAndRegisterKey(keyHandle2, "test.domain"));

  keys = await testAuthenticator.registeredKeys();
  assert_equals(keys.length, 2);

  keys = await testAuthenticator.clearRegisteredKeys();

  keys = await testAuthenticator.registeredKeys();
  assert_equals(keys.length, 0);
}, "Methods of VirtualAuthenticator work.");

</script>
